package com.atguigu.service;

import com.atguigu.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class UserDetailsServiceImpl implements org.springframework.security.core.userdetails.UserDetailsService {
  static Map<String, User> map =   new HashMap<String, User>();

  static {
    com.atguigu.pojo.User user1 =  new com.atguigu.pojo.User();
    user1.setUsername("admin");
    user1.setPassword("{noop}admin");
    user1.setTelephone("123");

    com.atguigu.pojo.User user2 =  new com.atguigu.pojo.User();
    user2.setUsername("zhangsan");
    user2.setPassword("{noop}123");
    user2.setTelephone("321");

    map.put(user1.getUsername(),user1);
    map.put(user2.getUsername(),user2);
  }

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = map.get(username);
    if (user==null){
      return null;
    }
      String passwordInDb ="{noop}" + user.getPassword();
      //授权，后期需要改为查询数据库动态获得用户拥有的权限和角色
      List<GrantedAuthority> lists = new ArrayList<>();
      lists.add(new SimpleGrantedAuthority("add"));
      lists.add(new SimpleGrantedAuthority("delete"));
      lists.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
    System.out.println("lists = " + lists);
    System.out.println("lists = " + lists);
    System.out.println("lists = " + lists);

      org.springframework.security.core.userdetails.User userobj = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), lists);

    return new org.springframework.security.core.userdetails.User(username,passwordInDb,lists);
  }
}
